package juc;


/*
 * Author：江松
 * Date：2023/3/28 10:29
 *
 原子
 */

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicDemo {

    public static void main(String[] args) {

        AtomicRunnable runnable = new AtomicRunnable();
        Thread t1 = new Thread(runnable,"窗口一");
        Thread t2 = new Thread(runnable,"窗口二");
        t1.start();
        t2.start();
    }
}

class AtomicRunnable implements Runnable{
    //共享的火车票变量
    private static AtomicInteger atomic = new AtomicInteger(100);

    //重寫run方法
    @Override
    public void run() {
        while (atomic.get() > 0){
            try {
                //休眠一下 方便出现并发问题
                Thread.sleep(50);
            }catch (Exception e){
                e.getMessage();
            }
            sale();
        }
    }
    //卖票
    public void sale(){
        if(atomic.get() > 0){
            Integer count=  100 - atomic.getAndDecrement() + 1; //使用底层方法getAndDecrement()  自-1；
            System.out.println(Thread.currentThread().getName()+ "," + count);//获取当前值
        }
    }


}
